package com.example.testmmkv

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.lib_common.utils.MMKVUtils
import com.example.lib_common.utils.ToolUtils

class MainActivity : AppCompatActivity() {
    private val TAG = "testMMkvLog"
    private val REQUEST_PERMISSION_CODE = 100
    private var PERMISSIONS = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
    private val tvBack:TextView by lazy { findViewById(R.id.tv_back) }
    private val textView:TextView by lazy { findViewById(R.id.tv_test) }
    private val tvAge:TextView by lazy { findViewById(R.id.tv_age) }
    private val tvAccount:TextView by lazy { findViewById(R.id.tv_account) }
    private val tvSex:TextView by lazy { findViewById(R.id.tv_sex) }
    private val tvBirthday:TextView by lazy { findViewById(R.id.tv_birthday) }
    private val tvIdentity:TextView by lazy { findViewById(R.id.tv_identity) }
    private val tvAmount:TextView by lazy { findViewById(R.id.tv_amount) }
    private val tvAddress:TextView by lazy { findViewById(R.id.tv_address) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 检查并请求权限
        if (checkPermissions()) {
            // 已经有权限，执行文件读写操作
            performFileOperations()
        } else {
            // 请求权限
            requestPermission()
        }
    }

    private fun initData() {
        val userName = MMKVUtils.getInstance().decodeString("key1")
        val age: Int = MMKVUtils.getInstance().decodeInt("age")
        val sex: String = MMKVUtils.getInstance().decodeString("sex")
        val address: String = MMKVUtils.getInstance().decodeString("address")
        val birthday: String = MMKVUtils.getInstance().decodeString("birthday")
        val account: String = MMKVUtils.getInstance().decodeString("account")
        val identity: Boolean = MMKVUtils.getInstance().decodeBoolean("identity")
        val amount: Double = MMKVUtils.getInstance().decodeDouble("amount")
        textView.text = "用户姓名：$userName"
        tvAddress.text = "用户地址：$address"
        tvAge.text = "用户年龄：$age"
        tvAccount.text = "用户账号：$account"
        tvAmount.text = "用户金额：￥${amount}元"
        tvBirthday.text = "用户生日：$birthday"
        tvIdentity.text = "用户身份：$identity"
        tvSex.text = "用户性别:$sex"
        Log.d(TAG, "====跨进程通信测试数据===$userName$age$sex$address$birthday$account$identity$account$amount")
        tvBack.setOnClickListener {
            try {
                MMKVUtils.getInstance().encode("backKey","用户小明回到原来的应用")
                //finish()
                ToolUtils.openApp("com.example.mmkvdemo", this@MainActivity)
                // ToolUtils.openThirdApp("om.example.testmmkv", this@MainActivity)
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }

    private fun checkPermissions(): Boolean {
        when {
            Build.VERSION.SDK_INT >= 33 -> {
                val permissions = arrayOf(
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                )
                for (permission in permissions) {
                    return Environment.isExternalStorageManager()
                }
            }

            else -> {
                for (permission in PERMISSIONS) {
                    if (ContextCompat.checkSelfPermission(
                            this,
                            permission
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        return false
                    }
                }
            }
        }
        return true
    }

    private fun requestPermission() {
        when {
            Build.VERSION.SDK_INT >= 33 -> {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.READ_MEDIA_IMAGES,Manifest.permission.READ_MEDIA_AUDIO,Manifest.permission.READ_MEDIA_VIDEO,Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO),
                    REQUEST_PERMISSION_CODE
                )
            }

            else -> {
                ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_CODE)
            }
        }
    }

    private fun performFileOperations() {
        //BaseApplication.Instance.initMMKV()
        initData()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSION_CODE) {
            var allPermissionsGranted = true
            for (result in grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false
                    break
                }
            }
            if (allPermissionsGranted) {
                // 权限已授予，执行文件读写操作
                performFileOperations()
            } else {
                // 权限被拒绝，处理权限请求失败的情况
                requestPermission()
            }
        }
    }
}